﻿package Gameplay 
{
	import com.junkbyte.console.Cc;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	
	public class Battlefield extends Sprite 
	{
		private const CXOffset:int = Constants.DEFAULT_SHIPS_FIELDS_OFFSET;		
		private const CYOffset:Number = CXOffset * Math.cos(45);
		private const CScaleFactor:Number = Constants.CELLS_COUNT / Constants.DEFAULT_CELLS_COUNT;
		
		private var FCenter:Point;
		private var FPlayerShips:ShipsField;
		private var FEnemyShips:ShipsField;
		private var FFieldSize:int;		
		
		//test
		private var FSelector:GridSelector;
		
		public function Battlefield():void
		{
			FCenter = new Point();			
			FSelector = new GridSelector();			
			FPlayerShips = new ShipsField();			
			FEnemyShips = new ShipsField();		
			addChild(FPlayerShips);
			addChild(FEnemyShips);		
			FFieldSize = Constants.DEFAULT_SHIPS_FIELD_SIZE;
			addEventListener(Event.ADDED_TO_STAGE, OnAddedToStage);
			
			FEnemyShips.Selector = FSelector;
		}		
		
		private function OnAddedToStage(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, OnAddedToStage);
			OnStageResize();
			stage.addEventListener(Event.RESIZE, OnStageResize);
		}
		
		private function OnStageResize(e:Event = null):void 
		{
			graphics.clear();
			graphics.beginFill(0, 0);
			graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
			graphics.endFill();
			
			FFieldSize = Constants.DEFAULT_SHIPS_FIELD_SIZE * stage.stageWidth / Constants.DEFAULT_STAGE_WIDTH;
			FFieldSize = Math.min(Constants.MAX_FIELD_SIZE, FFieldSize);						
			FCenter.x = stage.stageWidth / 2;
			FCenter.y = stage.stageHeight / 2;
			
			FPlayerShips.Size = FFieldSize;			
			FEnemyShips.Size = FFieldSize;	
			
			Cc.log('Ships field width = ' + FFieldSize);
			Cc.log('Ships field width original = ' + FPlayerShips.width + ', ' + FEnemyShips.width);
			Cc.log('Ships field width difference = ' + Number(FPlayerShips.width - FFieldSize).toFixed(3));
			
			var vDif:Number = FPlayerShips.width - FFieldSize;
			FFieldSize = FPlayerShips.width;			
			FPlayerShips.x = FCenter.x - FFieldSize * 0.75 - CXOffset + Math.SQRT2;
			FEnemyShips.x = FCenter.x - FFieldSize * 0.25 + CXOffset - Math.SQRT2;
			FFieldSize /= 4;
			FPlayerShips.y = FCenter.y - FPlayerShips.height * 0.75 - CYOffset - Math.SQRT1_2;
			FEnemyShips.y = FCenter.y - FEnemyShips.height * 0.25 + CYOffset + Math.SQRT1_2;
			
			trace(FPlayerShips.y - FEnemyShips.y);
			
			FFieldSize *= 4;			
		}
	}
}